package com.qd.panda.service.commodity;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dict.OperatorDictTemplate;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.commodity.CommodityClassificationListDTO;
import com.qd.common.panda.domain.entity.commodity.CommodityDTO;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.enums.BaseTableEnum;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.mapper.commodity.CommodityMapper;
import com.qd.panda.model.Commodity;
import com.qd.panda.model.CommodityStatistics;
import com.qd.panda.service.AsyncService;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.person.AuthTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 商品信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class CommodityService extends BaseService<CommodityMapper, Commodity> {

    private static final String PREFIX_ID = "panda_commodity_commodityId_{0}";

    private final RedisTemplateUtil<Commodity> redisTemplateUtil;
    private final CommodityDescService commodityDescService;
    private final CommodityPicService commodityPicService;
    private final CommodityClassificationListService commodityClassificationListService;
    private final OperatorDictTemplate operatorDictTemplate;
    private final AsyncService asyncService;
    private final AuthTokenService authTokenService;

    @Resource
    private HttpServletRequest request;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CommodityDTO save(CommodityDTO dto) {
        final Commodity model = dtoToModel(dto);
        model.setIsDeleted(ConstantDto.DICT_DELETE_NO);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public CommodityDTO update(CommodityDTO dto) {
        final Commodity historyModel = Optional.ofNullable(getById(dto.getCommodityId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final Commodity model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<Commodity> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<Commodity> mList) {
        final List<String> ids = mList.stream().map(Commodity::getCommodityId).collect(toList());
        final List<Commodity> historyModelList = checkIds(ids);
        try {
            super.getBaseMapper().batchUpdate(mList);
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param commodityId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String commodityId) {
        final Commodity historyModel = Optional.ofNullable(getById(commodityId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            LocalDateTime now = LocalDateTime.now();
            historyModel.setDeleteTime(now);
            if (!super.removeById(historyModel)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        ids.forEach(this::removeById);
    }

    /**
     * 批量删除
     *
     * @param deleteList 删除集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatch(List<Commodity> deleteList) {
        try {
            if (!super.removeByIds(deleteList)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(deleteList);
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(CommodityDTO dto) {
        final QueryWrapper<Commodity> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param commodityId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String commodityId) {
        boolean exists = false;
        if (StringUtils.hasLength(commodityId)) {
            final Commodity model = getById(commodityId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param commodityId 主键
     * @return 单条记录
     */
    public Commodity getById(String commodityId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, commodityId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(commodityId), Commodity.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param commodityId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CommodityDTO getByIdDto(String commodityId) {
        CommodityDTO commodityDTO = Optional.ofNullable(getById(commodityId)).map(this::modelToDto).orElse(null);
        Optional.ofNullable(commodityDTO).ifPresent(dto -> {
            dto.setPicList(commodityPicService.getListByCommodityId(dto.getCommodityId()));
            dto.setCommodityDesc(commodityDescService.getByIdDto(dto.getCommodityId()));
            List<CommodityClassificationListDTO> commodityClassificationList = commodityClassificationListService.getListByCommodityId(commodityId);
            if (!commodityClassificationList.isEmpty()) {
                commodityDTO.setClassificationList(commodityClassificationList);
            }
            saveCommodityStatistics(commodityId);
        });

        return commodityDTO;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    public Commodity getOne(CommodityDTO dto) {
        final QueryWrapper<Commodity> queryWrapper = createQueryWrapper(dto);
        Commodity model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public CommodityDTO getOneDto(CommodityDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    public List<Commodity> getList(CommodityDTO dto) {
        final QueryWrapper<Commodity> queryWrapper = createQueryWrapper(dto);
        final List<Commodity> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<CommodityDTO> getListDto(CommodityDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<CommodityDTO> page(Page<Commodity> page, CommodityDTO dto) {
        final QueryWrapper<Commodity> queryWrapper = createQueryWrapper(dto);
        Page<Commodity> iPage = baseMapper.selectPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(this::modelToDtoList);
        queryWrapper.clear();
        return iPage.convert(this::modelToDto);
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<CommodityDTO> appPage(Page<Commodity> page, CommodityDTO dto) {
        Integer productStatisticsType = null;
        String desc = dto.getDesc();
        String asc = dto.getAsc();
        final QueryWrapper<Commodity> queryWrapper = createQueryWrapper(dto, "t1.");
        queryWrapper.eq("t1.is_deleted", ConstantDto.DICT_DELETE_NO);
        if (StringUtils.hasLength(dto.getClassificationCode())) {
            Object[] classificationCodes = dto.getClassificationCode().split(",");
            if (classificationCodes.length == 1) {
                queryWrapper.eq("t3.classification_code", dto.getClassificationCode());
            } else {
                queryWrapper.in("t3.classification_code", classificationCodes);
            }
            queryWrapper.eq("t3.is_deleted", ConstantDto.DICT_DELETE_NO);
        }
        if (StringUtils.hasLength(desc)) {
            String[] split = desc.split(",");
            productStatisticsType = buildStatisticsType(split, productStatisticsType);
            List<String> descList = List.of(split);
            queryWrapper.orderByDesc(descList);
        }
        if (StringUtils.hasLength(asc)) {
            String[] split = asc.split(",");
            productStatisticsType = buildStatisticsType(split, productStatisticsType);
            List<String> ascList = List.of(split);
            queryWrapper.orderByAsc(ascList);
        }
        final IPage<CommodityDTO> iPage = baseMapper.appPage(page, queryWrapper, productStatisticsType, dto.getClassificationCode());
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(commodityDTO -> {
            List<CommodityClassificationListDTO> list = commodityClassificationListService.getListByCommodityId(commodityDTO.getCommodityId());
            if (!list.isEmpty()) {
                commodityDTO.setClassificationList(list);
            }
            buildDisplay(commodityDTO);
        }));
        queryWrapper.clear();
        return iPage;
    }

    private static Integer buildStatisticsType(String[] split, Integer productStatisticsType) {
        for (String s : split) {
            if ("t2.quantity".equals(s)) {
                productStatisticsType = PandaConstant.PRODUCT_STATISTICS_TYPE_2;
                break;
            }
        }
        return productStatisticsType;
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(Commodity model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCommodityId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<Commodity> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getCommodityId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public CommodityDTO modelToDto(Commodity model) {
        if (null == model) {
            return null;
        }
        final CommodityDTO dto = new CommodityDTO();
        dto.setCommodityId(model.getCommodityId());
        dto.setCommodityCode(model.getCommodityCode());
        dto.setCommodityName(model.getCommodityName());
        dto.setCommodityIntroduction(model.getCommodityIntroduction());
        dto.setCommodityPrice(model.getCommodityPrice());
        dto.setDiscountValue(model.getDiscountValue());
        dto.setUserDiscountMethods(model.getUserDiscountMethods());
        dto.setUserDiscountValue(model.getUserDiscountValue());
        dto.setCommodityPic(model.getCommodityPic());
        dto.setAddTime(model.getAddTime());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setDeleteTime(model.getDeleteTime());
        dto.setIsDeleted(model.getIsDeleted());
        dto.setEnable(model.getEnable());
        dto.setSupplier(model.getSupplier());
        dto.setOperator(model.getOperator());
        dto.setOrgId(model.getOrgId());
        dto.setBrand(model.getBrand());
        dto.setDiscountMethods(model.getDiscountMethods());
        dto.setProductForm(model.getProductForm());
        dto.setCombinedCommodity(model.getCombinedCommodity());
        dto.setUserPrice(model.getUserPrice());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public Commodity dtoToModel(CommodityDTO dto) {
        if (null == dto) {
            return null;
        }
        final Commodity model = new Commodity();
        model.setCommodityId(dto.getCommodityId());
        model.setCommodityCode(dto.getCommodityCode());
        model.setCommodityName(dto.getCommodityName());
        model.setCommodityIntroduction(dto.getCommodityIntroduction());
        model.setCommodityPrice(dto.getCommodityPrice());
        model.setDiscountValue(dto.getDiscountValue());
        model.setUserDiscountMethods(dto.getUserDiscountMethods());
        model.setUserDiscountValue(dto.getUserDiscountValue());
        model.setCommodityPic(dto.getCommodityPic());
        model.setAddTime(dto.getAddTime());
        model.setUpdateTime(dto.getUpdateTime());
        model.setDeleteTime(dto.getDeleteTime());
        model.setIsDeleted(dto.getIsDeleted());
        model.setEnable(dto.getEnable());
        model.setSupplier(dto.getSupplier());
        model.setOperator(dto.getOperator());
        model.setOrgId(dto.getOrgId());
        model.setBrand(dto.getBrand());
        model.setDiscountMethods(dto.getDiscountMethods());
        model.setProductForm(dto.getProductForm());
        model.setCombinedCommodity(dto.getCombinedCommodity());
        model.setUserPrice(dto.getUserPrice());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(CommodityDTO dto) {
        operatorDictTemplate.execute(dto);
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<CommodityDTO> modelToDtoList(List<Commodity> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<Commodity> dtoToModelList(List<CommodityDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<Commodity> createQueryWrapper(CommodityDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<Commodity> createQueryWrapper(CommodityDTO dto, String tableAlias) {
        final QueryWrapper<Commodity> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getCommodityCode())) {
                queryWrapper.eq(tableAlias + "commodity_code", dto.getCommodityCode());
            }
            if (StringUtils.hasLength(dto.getCommodityName())) {
                queryWrapper.eq(tableAlias + "commodity_name", dto.getCommodityName());
            }
            if (StringUtils.hasLength(dto.getUserDiscountMethods())) {
                queryWrapper.eq(tableAlias + "user_discount_methods", dto.getUserDiscountMethods());
            }
            if (StringUtils.hasLength(dto.getEnable())) {
                queryWrapper.eq(tableAlias + "enable", dto.getEnable());
            }
            if (StringUtils.hasLength(dto.getBrand())) {
                Object[] brands = dto.getBrand().split(",");
                if (brands.length == 1) {
                    queryWrapper.eq(tableAlias + "brand", dto.getBrand());
                } else {
                    queryWrapper.in(tableAlias + "brand", brands);
                }
            }
            if (StringUtils.hasLength(dto.getSupplier())) {
                queryWrapper.eq(tableAlias + "supplier", dto.getSupplier());
            }
            if (StringUtils.hasLength(dto.getDiscountMethods())) {
                queryWrapper.eq(tableAlias + "discount_methods", dto.getDiscountMethods());
            }
            if (StringUtils.hasLength(dto.getProductForm())) {
                queryWrapper.eq(tableAlias + "product_form", dto.getProductForm());
            }
            if (StringUtils.hasLength(dto.getCombinedCommodity())) {
                queryWrapper.eq(tableAlias + "combined_commodity", dto.getCombinedCommodity());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<Commodity> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<Commodity> list = super.getBaseMapper().getAllList(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(Commodity::getCommodityId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }


    @Transactional(rollbackFor = Exception.class)
    public void removeAll() {
        List<String> all = super.getBaseMapper().getAll();
        if (!all.isEmpty()) {
            super.getBaseMapper().deleteAll(all);
            all.clear();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void enable(CommodityDTO dto) {
        CommodityDTO commodityDTO = new CommodityDTO();
        if (MbUtil.isNotExists(dto.getEnable(), BaseTableEnum.SF)) {
            throw new ApiException("是否启用值错误");
        }
        commodityDTO.setEnable(dto.getEnable());
        commodityDTO.setCommodityId(dto.getCommodityId());
        commodityDTO.setUpdateTime(LocalDateTime.now());
        commodityDTO.setOperator(SecurityUtils.getLoginUser().getUserId());
        commodityDTO.setOrgId(SecurityUtils.getLoginUser().getCurrentOrgId());
        update(commodityDTO);
        commodityDTO.freeData();
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveCommodityList(List<Commodity> commodityList) {
        if (!commodityList.isEmpty()) {
            saveBatch(commodityList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateCommodityList(List<Commodity> commodityList) {
        List<String> commodityIds = commodityList.stream().map(Commodity::getCommodityId).collect(toList());
        List<Commodity> oldList = super.getBaseMapper().getAllList(commodityIds);
        List<Commodity> addList = new ArrayList<>(1024);
        List<Commodity> updateList = new ArrayList<>(1024);
        List<Commodity> deleteList = new ArrayList<>(1024);
        List<String> oldIdsList = null;
        if (!oldList.isEmpty()) {
            oldIdsList = oldList.stream().map(Commodity::getCommodityId).collect(toList());
        }
        for (Commodity commodity : commodityList) {
            if (null == oldIdsList || oldIdsList.isEmpty()) {
                if (commodity.getIsDeleted().equals(ConstantDto.DICT_DELETE_NO)) {
                    addList.add(commodity);
                }
            } else {
                if (CollUtil.contains(oldIdsList, commodity.getCommodityId())) {
                    if (commodity.getIsDeleted().equals(ConstantDto.DICT_DELETE_NO)) {
                        updateList.add(commodity);
                    } else {
                        deleteList.add(commodity);
                    }
                } else {
                    if (commodity.getIsDeleted().equals(ConstantDto.DICT_DELETE_NO)) {
                        addList.add(commodity);
                    }
                }
            }
        }
        if (!addList.isEmpty()) {
            saveBatch(addList);
            addList.clear();
        }
        if (!updateList.isEmpty()) {
            updateBatchIds(updateList);
            updateList.clear();
        }
        if (!deleteList.isEmpty()) {
            List<String> deleteListIds = deleteList.stream().map(Commodity::getCommodityId).collect(toList());
            if (!oldList.isEmpty()) {
                List<String> idsNoDel = oldList.stream().filter(cl -> cl.getIsDeleted().equals(ConstantDto.DICT_DELETE_NO)).map(Commodity::getCommodityId).collect(toList());
                if (!idsNoDel.isEmpty()) {
                    List<String> deleteIds = new ArrayList<>(CollUtil.intersection(deleteListIds, idsNoDel));
                    if (!deleteIds.isEmpty()) {
                        for (Commodity commodity : deleteList) {
                            removeById(commodity.getCommodityId());
                        }
                        deleteIds.clear();
                    }
                }
            }
            deleteListIds.clear();
            deleteList.clear();
        }
        commodityIds.clear();
    }

    private void saveCommodityStatistics(String commodityId) {
        String userId = null;
        LoginUser loginUser = authTokenService.getLoginUser(request);
        if (null != loginUser) {
            userId = loginUser.getUserId();
        }
        CommodityStatistics commodityStatistics = new CommodityStatistics();
        commodityStatistics.setCommodityId(commodityId);
        if (StringUtils.hasLength(userId)) {
            commodityStatistics.setUserId(userId);
        }
        commodityStatistics.setAddTime(LocalDateTime.now());
        commodityStatistics.setProductStatisticsType(PandaConstant.PRODUCT_STATISTICS_TYPE_1);
        commodityStatistics.setSyncState(PandaConstant.SYNC_STATE_0);
        asyncService.saveCommodityStatistics(commodityStatistics);
    }

    @Transactional(readOnly = true)
    public Object idToDisplay(String commodityId) {
        if (StringUtils.hasLength(commodityId)) {
            return Optional.ofNullable(getById(commodityId)).map(Commodity::getCommodityName).orElse("");
        }
        return "";
    }
}